package com.foreknow.elm.dao.impl;

import com.foreknow.elm.dao.OrderdetailetDao;
import com.foreknow.elm.po.Food;
import com.foreknow.elm.po.OrderDetaiLet;
import com.foreknow.elm.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


public class OrderdetailetDaoImpl implements OrderdetailetDao {
    private Connection con;
    private PreparedStatement pst;
    private ResultSet rs;

    @Override
    public Integer saveOrdersdetailrt(List<OrderDetaiLet> list) throws SQLException {
        int result = 0;
        StringBuffer s = new StringBuffer("insert into orderdetailet(orderId,foodId,quantity) values");
        for (OrderDetaiLet orderDetaiLet : list) {
            s.append("(" + orderDetaiLet.getOrderId() + "," + orderDetaiLet.getFoodId() + "," + orderDetaiLet.getQuantity() + ")" + ",");
        }
        //去掉sql语句中的最后一个逗号
        String sql = s.toString().substring(0, s.toString().length() - 1);
        try {
            con = DBUtil.getConnection();
            pst = con.prepareStatement(sql);
            result = pst.executeUpdate();
        } finally {
            DBUtil.close(pst);
        }
        return result;
    }

    @Override
    public List<OrderDetaiLet> selectOrderDetaiLet(Integer orderId) throws SQLException {
        List<OrderDetaiLet> letList = new ArrayList<>();
        String sql = "select * from orderdetailet o,food f where o.foodId=f.foodId and o.orderId=?";
        try {
            con = DBUtil.getConnection();
            pst = con.prepareStatement(sql);
            pst.setInt(1,orderId);
            rs = pst.executeQuery();
            while (rs.next()) {
                Food food = new Food();
                food.setFoodId(rs.getInt("foodId"));
                food.setFoodName(rs.getString("foodName"));
                food.setFoodExplain(rs.getString("foodExplain"));
                food.setFoodImg(rs.getString("foodImg"));
                food.setFoodPrice(rs.getDouble("foodPrice"));
                food.setBusinessId(rs.getInt("businessId"));
                food.setRemarks(rs.getString("remarks"));
                OrderDetaiLet orderDetaiLet = new OrderDetaiLet();
                orderDetaiLet.setOdId(rs.getInt("odId"));
                orderDetaiLet.setOrderId(rs.getInt("orderId"));
                orderDetaiLet.setFoodId(rs.getInt("foodId"));
                orderDetaiLet.setQuantity(rs.getInt("quantity"));
                orderDetaiLet.setFoods(food);
                letList.add(orderDetaiLet);
            }
        } finally {
            DBUtil.close(pst);
        }
        return letList;
    }
}
